﻿using Application.Dto;
using Application.IAppSrevices;
using AutoMapper;
using Domain.Entitys;
using Hangfire;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using UI.Hubs;

namespace UI.Controllers
{
    public class SGController : Controller
    {
        private readonly ICPCService cPCService;
        private readonly ISGService sGService;
        private readonly IHFService hFService;
        private readonly ISSDService sSDService;
        private readonly IMapper mapper;
        private readonly ISGDService sGDService;
        private readonly IEmailService emailService;
        private readonly IDistributedCache distributedCache;
        private readonly ILogger<SGController> logger;

        public SGController(ICPCService cPCService,ISGService sGService,IHFService hFService,ISSDService sSDService,IMapper mapper,ISGDService sGDService,IEmailService emailService, IDistributedCache distributedCache,ILogger<SGController> logger)
        {
            this.cPCService = cPCService;
            this.sGService = sGService;
            this.hFService = hFService;
            this.sSDService = sSDService;
            this.mapper = mapper;
            this.sGDService = sGDService;
            this.emailService = emailService;
            this.distributedCache = distributedCache;
            this.logger = logger;
        }
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询薪酬发放方式下拉框数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> SGSelectOption()
        {
            return Json(await cPCService.CPCFillAsync("薪酬发放方式"));
        }

        /// <summary>
        /// 薪酬记录发放登记页面
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public IActionResult SGJGSelect(int num)
        {
            TempData["num"] = num;
            TempData["num2"] = num;
            return View();
        }

        /// <summary>
        /// 获取薪酬记录需要发放数据
        /// </summary>
        /// <returns></returns>
        public IActionResult GetNewSG()
        {
            int num = (int)TempData["num"];
            return Json(sGService.GetNewSG(num));
        }

        /// <summary>
        /// 薪酬发放登记页面
        /// </summary>
        /// <returns></returns>
        public IActionResult SGRegistration(string kindId,string kindName)
        {
            TempData["kindId"] = kindId;
            ViewBag.kindName = kindName;
            int num = (int)TempData["num2"];
            ViewBag.num = num;
            string userName = HttpContext.Session.GetString("UTrueName");
            ViewBag.UserTrueName = userName;
            return View();
        }

        /// <summary>
        /// 根据1，2，3级编号查询对应数据
        /// </summary>
        /// <returns></returns>
        public IActionResult HFByKindId()
        {
            string id = TempData["kindId"].ToString();
            return Json(hFService.HFByKindId(id));
        }

        /// <summary>
        /// 根据薪酬编号查询数据
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public async Task<IActionResult> SSDSelectBySid(string sid)
        {
            List<SSD> sG = null;
            string key = "SSD" + sid;
            string s = await distributedCache.GetStringAsync(key);
            if (s == null)
            {
                logger.LogInformation("从数据库根据薪酬编号查询数据");
                sG = await sSDService.SSDSelectBySid(sid);
                var opt = new DistributedCacheEntryOptions();
                opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);//30秒后失效
                await distributedCache.SetStringAsync(key, JsonConvert.SerializeObject(sG), opt);
            }
            else
            {
                logger.LogInformation("从分布式缓存根据薪酬编号查询数据");
                sG = JsonConvert.DeserializeObject<List<SSD>>(s);
            }
            return Json(sG);
        }

        /// <summary>
        /// 添加薪酬发放登记信息
        /// </summary>
        /// <param name="sGAddDto"></param>
        /// <returns></returns>
        /// <returns></returns>
        [TypeFilter(typeof(SingarFilterAttribute), Arguments = new object[] { "薪酬发放管理" })]
        [HttpPost("SG/SGAddAsync")]
        public async Task<IActionResult> SGAddAsync(SGAddDto sGAddDto)
        {
            int num = await sGService.SGAddAsync(sGAddDto);
            return Json(num);
        }

        /// <summary>
        /// 添加薪酬详细信息数据
        /// </summary>
        /// <param name="sGDAddDtos"></param>
        /// <returns></returns>
        [HttpPost("SG/SGDAddAsync")]
        public async Task<IActionResult> SGDAddAsync(List<SGDAddDto> sGDAddDtos)
        {
            int num = await sGDService.SGDAddAsync(sGDAddDtos);
            return Json(num);
        }

        /// <summary>
        /// 修改人力资源档案实发，应发金额
        /// </summary>
        /// <param name="hFUpdateSalarySums"></param>
        /// <returns></returns>
        [HttpPut("SG/SGUpdateSalarySumAsync")]
        public async Task<IActionResult> SGUpdateSalarySumAsync(List<HF> hFs)
        {
            int num = await hFService.HFUpdateSalarySumAsync(hFs);
            return Json(num);
        }

        /// <summary>
        /// 显示薪酬发放登记信息
        /// </summary>
        /// <returns></returns>
        public IActionResult SGChangePage()
        {
            return View();
        }

        /// <summary>
        /// 分页查询薪酬发放数据
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IActionResult SGSelectFnYe(int currentPage,int pageSize)
        {
            FenYe<SG> fenYe = new FenYe<SG>()
            {
                CurrentPage = currentPage,
                PageSize = pageSize
            };
            sGService.SGSelectFnYe(fenYe);
            return Json(fenYe);
        }

        /// <summary>
        /// 薪酬发放复核页面
        /// </summary>
        /// <returns></returns>
        public IActionResult SGReviewPage(string id)
        {
            TempData["sid"] = id;
            string userName = HttpContext.Session.GetString("UTrueName");
            ViewBag.UserTrueName = userName;
            return View();
        }

        /// <summary>
        /// 根据薪酬发放编号查询对应数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("SG/SGByIdAsync")]
        public async Task<IActionResult> SGByIdAsync()
        {
            string id = TempData["sid"].ToString();
            SG sG = null;
            string key = "SG" + id;
            string s = await distributedCache.GetStringAsync(key);
            if (s == null)
            {
                logger.LogInformation("从数据库根据薪酬发放编号查询对应数据");
                sG = await sGService.SGByIdAsync(id);
                var opt = new DistributedCacheEntryOptions();
                opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);
                await distributedCache.SetStringAsync(key,JsonConvert.SerializeObject(sG),opt);
            }
            else
            {
                logger.LogInformation("从分布式缓存根据薪酬发放编号查询对应数据");
                sG = JsonConvert.DeserializeObject<SG>(s);
            }
            return Json(sG);
        }

        /// <summary>
        /// 根据薪酬发放编号查询对应薪酬详细数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("SG/SGDByIdAsync")]
        public async Task<IActionResult> SGDByIdAsync(string id)
        {
            List<SGD> sgDList = null;
            string key = "SGD" + id;
            string s = await distributedCache.GetStringAsync(key);
            if (s == null)
            {
                logger.LogInformation("从数据库根据薪酬发放编号查询对应薪酬详细数据");
                sgDList = await sGDService.SGDBySidAsync(id);
                var opt = new DistributedCacheEntryOptions();
                opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);
                await distributedCache.SetStringAsync(key,JsonConvert.SerializeObject(sgDList),opt);
            }
            else
            {
                logger.LogInformation("从分布式缓存根据薪酬发放编号查询对应薪酬详细数据");
                sgDList = JsonConvert.DeserializeObject<List<SGD>>(s);
            }
            return Json(sgDList);
        }

        /// <summary>
        /// 修改薪酬发放通过数据
        /// </summary>
        /// <param name="sG"></param>
        /// <returns></returns>
        [HttpPut("SG/SGUpdateAsync")]
        public async Task<IActionResult> SGUpdateAsync(SG sG)
        {
            int num = await sGService.SGUpdateAsync(sG);
            return Json(num);
        }

        /// <summary>
        /// 修改薪酬发放详细数据
        /// </summary>
        /// <param name="sGDs"></param>
        /// <returns></returns>
        [HttpPut("SG/SGDUpdateAsync")]
        public async Task<IActionResult> SGDUpdateAsync(List<SGD> sGDs)
        {
            int num = await sGDService.SGDUpdateAsync(sGDs);
            return Json(num);
        }

        /// <summary>
        /// 多条件查询薪酬发放信息页面
        /// </summary>
        /// <returns></returns>
        public IActionResult SGSelectWherePage()
        {
            return View();
        }

        /// <summary>
        /// 多条件查询薪酬发放信息数据页面
        /// </summary>
        /// <returns></returns>
        public IActionResult SGSelectWherePageInfo(string id, string name, string startDate, string endDate)
        {
            if (!string.IsNullOrEmpty(id))
            {
                TempData["id"] = id;
            }
            if (!string.IsNullOrEmpty(name))
            {
                TempData["name"] = name;
            }
            if (!string.IsNullOrEmpty(startDate))
            {
                TempData["startDate"] = startDate;
            }
            if (!string.IsNullOrEmpty(endDate))
            {
                TempData["endDate"] = endDate;
            }
            return View();
        }

        /// <summary>
        /// 多条件查询薪酬发放数据
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IActionResult SGSelectWhere(int currentPage,int pageSize)
        {
            FenYe<SG> fenYe = new FenYe<SG>()
            {
                CurrentPage = currentPage,
                PageSize = pageSize
            };
            string id = "";
            string name = "";
            string startDate = "";
            string endDate = "";
            if (TempData["id"] != null)
            {
                id = TempData["id"].ToString();
            }
            if (TempData["name"] != null)
            {
                name = TempData["name"].ToString();
            }
            if (TempData["startDate"] != null)
            {
                startDate = TempData["startDate"].ToString();
            }
            if (TempData["endDate"] != null)
            {
                endDate = TempData["endDate"].ToString();
            }
            sGService.SGSelectWhere(fenYe,id,name,startDate,endDate);
            return Json(fenYe);
        }

        /// <summary>
        /// 点击查询薪酬发放详细信息数据页面
        /// </summary>
        /// <returns></returns>
        public IActionResult SGByIdPageInfo(string id)
        {
            TempData["sid"] = id;
            return View();
        }

        /// <summary>
        /// 根据人力资源编号查询数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("SG/HFByIDReviewAsync")]
        public async Task<IActionResult> HFByIDReviewAsync(string id)
        {
            return Json( await hFService.HFByIDReviewAsync(id));
        }

        [HttpPut("SG/SendMail")]
        public IActionResult SendMail(List<HF> hFs)
        {
            //每月1号执行更新操作
            RecurringJob.AddOrUpdate("SGUpdateJob", () =>
            SGUpdateSalarySumAsync(hFs), "0 0 0 1 * ?");
            return Json("Email Initiated");
        }
    }
}
